package com.beyond.market.user.controller;

import com.beyond.market.user.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("name", "张三");
        return "/index";   //thymeleaf->  /templates/index.html
    }

    @RequestMapping("/add")
    public String add(){
        return "/user/add";   //   thymeleaf -->  /templates/user/add.html
    }

    @RequestMapping("/remove")
    public String remove(){
        return "/user/remove";   //   thymeleaf -->  /templates/user/add.html
    }

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    @RequestMapping("/unauthorizedUrl")
    public String unauthorizedUrl(){
        return "/unauthorizedUrl";
    }

    @RequestMapping("/userLogin")
    public String userLogin(String username,String userpsd,Model model){
        //通过全局对象SecurityUtils得到主角
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken token = new UsernamePasswordToken(username,userpsd);
        try {
            //登录如果不抛异常，则跳转到首页
            //subject把token传给认证方法，返回来的此人的相关信息。info.密码拿出来和token参数的密码比较，如果一样则登录成功
            subject.login(token);
            return "redirect:/index";    //如果登录成功重定向到首页，登录状态写入到session中
        }catch(UnknownAccountException e){
            model.addAttribute("msg","查无此用户");
            return "/login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "/login";
        }
    }
}